package com.chj.design.sk;

import java.util.HashMap;
import java.util.Map;

public class Code10_Memento2 {
	public static class Originator {
		private String state;

		public void setState(String state) {
			this.state = state;
		}

		public String getState() {
			return this.state;
		}

		/**
		 * 保存当前状态到备忘录
		 */
		public Memento saveToMemento() {
			System.out.println("Saving current state: " + state);
			return new Memento(this.state);
		}

		/**
		 * 读取备忘录，恢复保存的状态
		 */
		public void restoreState(Memento memento) {
			System.out.println("Restore state");
			this.state = memento.getSavedState();
		}

		/**
		 * 备忘录，存储当前Originator状态
		 */
		public static class Memento {
			final String state;

			public Memento(String s) {
				this.state = s;
			}

			public String getSavedState() {
				return this.state;
			}
		}
	}

	/**
	 * 管理者
	 */
	public static class Caretaker {
		private final Map<String, Originator.Memento> mementoMap = new HashMap<>();

		/**
		 * 保存状态
		 */
		public synchronized void addMemento(String id, Originator.Memento memento) {
			mementoMap.put(id, memento);
		}

		/**
		 * 读取状态
		 */
		public synchronized Originator.Memento getMemento(String id) {
			return mementoMap.get(id);
		}

		/**
		 * 删除状态
		 */
		public synchronized Originator.Memento deleteMemento(String id) {
			return mementoMap.remove(id);
		}
	}

//	https://juejin.cn/post/6844903917868810248
	public static void main(String[] args) {
		Caretaker caretaker = new Caretaker();
		Originator originator = new Originator();
		// 设置状态：满血
		originator.setState("Full Blood");
		// 保存当前状态
		caretaker.addMemento("1", originator.saveToMemento());

		// 状态改变：半血
		originator.setState("Half Blood");
		System.out.println(originator.getState());
		// 读取保存状态
		originator.restoreState(caretaker.getMemento("1"));
		System.out.println(originator.getState());

	}
}
